<!-- 缓存菜单 -->
<template>
  <div class="tags flex items-center py-2px">
    <el-scrollbar
      ref="scrollbarRef"
      class="flex-1"
    >
      <div
        class="flex gap-1.5"
      >
        <el-tag
          v-for="item in tagsStore.tags"
          :ref="(e)=>(tags[item.path] = e)"
          :key="item.path"
          class="cursor-pointer"
          :effect="activeTag === item.path?'dark':'plain'"
          :closable="item.name !== 'home'"
          @close="tagEdit(item)"
          @click="tabClick(item)"
        >
          {{ item.label }}
        </el-tag>
      </div>
    </el-scrollbar>

    <el-popconfirm
      title="是否关闭所有标签？"
      @confirm="closeAll"
    >
      <template #reference>
        <el-button
          :icon="CloseBold"
          circle
        />
      </template>
    </el-popconfirm>
  </div>
</template>

<script setup>
import { CloseBold } from '@element-plus/icons-vue'
import useTagsStore from '@/store/tags'

const route = useRoute()
const router = useRouter()
const tagsStore = useTagsStore()

// 选中数据
const activeTag = ref('')

// 添加/打开 标签
const addTags = () => {
  if (!tagsStore.breadcrumb.length) return
  const bread = tagsStore.breadcrumb[tagsStore.breadcrumb.length - 1]

  if (bread.type === 3) {
    activeTag.value = ''
    return
  }

  activeTag.value = route.fullPath
  if (tagsStore.tags.some(v => v.path === route.fullPath)) return
  tagsStore.tags.push({
    label: bread.name,
    path: route.fullPath,
    name: route.name
  })
}

// 滚动位置
const scrollbarRef = ref(null)
const tags = ref({})
const moveToCurrentTag = async () => {
  await nextTick()
  if (!tags.value[activeTag.value]) return
  const activeLeft = tags.value[activeTag.value].$el.offsetLeft
  scrollbarRef.value.setScrollLeft(activeLeft)
  scrollbarRef.value.update()
}

const stop = watch(route, () => {
  if (!route.meta.requiresAuth) return
  addTags()
  moveToCurrentTag()
}, {
  immediate: true
})
onUnmounted(stop)

// 标签点击
const tabClick = (data) => {
  router.push(data.path)
}

// 标签关闭
const tagEdit = ({ path }) => {
  let activeName = activeTag.value

  if (activeName === path) {
    tagsStore.tags.forEach((tag, index) => {
      if (tag.path === path) {
        const nextTab = tagsStore.tags[index + 1] || tagsStore.tags[index - 1]
        if (nextTab) {
          activeName = nextTab.path
        }
      }
    })
    router.push(activeName)
  }
  tagsStore.tags = tagsStore.tags.filter((tab) => tab.path !== path)
}

// 关闭所有标签
const closeAll = () => {
  tagsStore.$reset()
  activeTag.value = tagsStore.tags[0].path
  router.push(activeTag.value)
}
</script>

<style scoped lang='scss'>
.tags{
  width: 100%;
  border-top: 1px solid #ccc;
}
</style>
